package serverComponent;

import java.util.Map;
import java.util.TreeMap;

import org.jivesoftware.whack.ExternalComponentManager;
import org.xmpp.component.Component;
import org.xmpp.component.ComponentException;
import org.xmpp.component.ComponentManager;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;

public class PubSubService
	implements Component 
{
	private ExternalComponentManager extManager;
	private IQHandler iqHandler;
	private MessageHandler messageHandler;
		
	// It contains the mapping between the user bare JID and its subscriptions
	private Map<String, Map<String, SubscriptionDetails>> subscriptions;
	
	private final String COMPONENT_NAME = "dispatcher.ciku.com";
	
	@Override
	public void initialize(JID arg0, ComponentManager arg1)
			throws ComponentException {
		extManager = (ExternalComponentManager) arg1;
		subscriptions = new TreeMap<String, Map<String, SubscriptionDetails>>();
		iqHandler = new IQHandler( this );
		messageHandler = new MessageHandler( this );
	}

	@Override
	public void processPacket( Packet packet )
	{
		if( packet instanceof IQ )
			iqHandler.processIQ((IQ) packet );
		else if( packet instanceof Message )
			messageHandler.processMessage((Message) packet );
	}
	

	@Override
	public void shutdown() {
		// TODO Auto-generated method stub
	}

	@Override
	public void start() {
		// TODO Auto-generated method stub
	}
	
	@Override
	public String getDescription() {
		return null;
	}

	@Override
	public String getName() {
		return COMPONENT_NAME;
	}

	public boolean hasSubscriptions( String bareJID ) {
		return subscriptions.containsKey( bareJID );
	}

	public Map<String, SubscriptionDetails> getSubscriptions( String bareJID ) {
		return subscriptions.get( bareJID );
	}
	
	public void addSubscription(String bareJID,
			Map<String, SubscriptionDetails> userSubscriptions) {
		subscriptions.put( bareJID, userSubscriptions );
	}
	
	public void removeSubscription(String bareJID) {
		subscriptions.remove( bareJID );
	}

	public void sendPacket( Packet packet ) {
		extManager.sendPacket( this, packet );
	}

}
